package org.az.netty_study.p14_netty综合案例2_聊天室.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.GroupQuitResponseMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.LoginRequestMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.LoginResponseMessage;
import org.az.netty_study.p14_netty综合案例2_聊天室.protocol.MessageCodecSharable;
import org.az.netty_study.p14_netty综合案例2_聊天室.protocol.ProcotolFrameDecoder;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.handler.*;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.service.UserServiceFactory;
import org.az.netty_study.p14_netty综合案例2_聊天室.server.session.SessionFactory;

@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        //一些可共享的handler
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        QuitRequestMessageHandler QUIT_HANDLER = new QuitRequestMessageHandler();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    //自定义消息编解码器
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    //指定时间内没有从channel读写数据，会触发一个IdleState#READER_IDLE或IdleState#WRITER_IDLE事件
                    ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                    //处理IdleState#READER_IDLE的handler,IdleState#READER_IDLE即是入站处理器，也是出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        //特殊事件处理器
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt instanceof IdleStateEvent event) {
                                //表示触发了读空闲事件
                                if (event.state() == IdleState.READER_IDLE) {
                                    log.info("读空闲已经超过5s，该连接可能假死了");
                                    ctx.channel().close();
                                }
                            }
                        }
                    });
                    //登录handler
                    ch.pipeline().addLast(LOGIN_HANDLER);
                    //单聊handler
                    ch.pipeline().addLast(CHAT_HANDLER);
                    //群聊创建handler
                    ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                    //群聊handler
                    ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                    //退出handler
                    ch.pipeline().addLast(QUIT_HANDLER);
                }
            });
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
